<template>
    <div class="container">
        <div>
            <van-nav-bar title="设置密码" left-text="返回" left-arrow @click-left="onClickLeft">
                <template #right>
                    <van-button type="success" @click="onSave">保存</van-button>
                </template>
            </van-nav-bar>
        </div>
        <p class="notice">设置用户密码,你可以用户的账号和密码登录，比如使用手机号+密码更快捷</p>

        <div>
            <van-cell-group inset>
                <van-field label="用户名" :model-value="phone" disabled />
                <van-field v-model="original_pwd" type="text" label="原密码" placeholder="填写原密码" @blur="checkPassword" />
                <van-field v-model="new_pwd" type="text" label="新密码" placeholder="填写新密码" />
                <van-field v-model="confirm_pwd" type="text" label="确认密码" placeholder="再次填写确认密码" />
            </van-cell-group>
        </div>
        <p class="notice">密码必须是8-16位的英文字母、数字组合</p>
    </div>

</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';
import http from '@/http';
import { useRouter } from 'vue-router';
const router = useRouter();
let original_pwd = ref('');
let new_pwd = ref('');
let confirm_pwd = ref('');
let phone = ref(localStorage.getItem('reginame'));
function checkPassword() {
    const data = {
        phone: phone.value,
        common_pwd: original_pwd.value
    }
    http.post('/patient/register_login/', data).then(res => {
        if (res.data.code == 200) {
            console.log("原密码正确", res.data);
            alert("原密码正确");
        } else {
            alert("原密码错误", res.data.msg)
        }
    }).catch(err => {
        console.log("请求失败", err);
    })
}


const onSave = async () => {
    if (new_pwd.value === confirm_pwd.value) {
        const data = {
            original_phone: localStorage.getItem('reginame'),
            new_pwd: new_pwd.value,
        };
        http.post('/patient/user_update/', data).then(response => {
            console.log('密码修改成功', response.data);
            router.push('/relogin');
            alert('密码修改成功');
        }).catch(error => {
            console.log('密码修改失败', error);
            alert('密码修改失败');
        });
    } else {
        alert("两次修改密码不一致，请重新输入")
    }
}
const onClickLeft = () => history.back();
</script>
<style scoped>
.container {
    background-color: #faf8f8;
    height: 200vh;
}

.phone_label {
    color: #bebcbc;
}

.notice {
    color: #bebcbc;
    font-size: 14px;
    margin-left: 10px;
}
</style>